package com.chinaunicom.system.controller;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.chinaunicom.system.model.User;
import com.chinaunicom.system.service.IUserService;

@Controller
@RequestMapping("/crm/login")
public class LoginController {

	@Resource
	private IUserService userService;

	@RequestMapping("/login")
	public void login(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		HttpSession session = request.getSession();
		

		if (request.getParameter("vUsername") != null
				&& !"".equals(request.getParameter("vUsername"))) {
			User u = userService.queryByUserName(request.getParameter("vUsername"));
			if (u == null) {
				// 表示账号不存在
				session.setAttribute("tip", "账号不存在");
				response.sendRedirect("/login.jsp");
			} else if (u.getvPassword().equals(
					request.getParameter("vPassword"))) {
				// 表示账号存在并且密码正确 登陆成功
				request.getRequestDispatcher("/WEB-INF/main.jsp").forward(
						request, response);
				session.setAttribute("isLogin", "yes");
				session.setAttribute("id", u.getnUserid());
			} else {
				// 表示密码错误
				session.setAttribute("tip", "密码错误");
				response.sendRedirect("/login.jsp");
			}
		} else {
			// 表示账号不存在
			session.setAttribute("tip", "账号不存在");
			response.sendRedirect("/login.jsp");
		}
	}

	@RequestMapping("/refresh")
	public void refresh(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		String isLogin = (String) session.getAttribute("isLogin");
		if ("yes".equals(isLogin)) {
			request.getRequestDispatcher("/WEB-INF/main.jsp").forward(request,
					response);
		} else {
			response.sendRedirect("/login.jsp");
		}
	}

}
